package com.youkeda.DesertCamel.service.impl;

import com.youkeda.DesertCamel.dao.dataobject.MrBookRecord;
import com.youkeda.DesertCamel.dao.dataobject.MrMeetingRoomPassword;
import com.youkeda.DesertCamel.dao.dataobject.MrUser;
import com.youkeda.DesertCamel.dao.mapper.MrBookRecordMapper;
import com.youkeda.DesertCamel.dao.mapper.MrMeetingRoomMapper;
import com.youkeda.DesertCamel.dao.mapper.MrMeetingRoomPasswordMapper;
import com.youkeda.DesertCamel.dao.mapper.MrUserMapper;
import com.youkeda.DesertCamel.model.BookRecord;
import com.youkeda.DesertCamel.model.Result;
import com.youkeda.DesertCamel.service.BookService;
import com.youkeda.DesertCamel.util.IdUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * BookServiceImpl的注释
 *
 * @author: Awake
 * @date: 2019-07-03 17:35
 **/
@Service
public class BookServiceImpl implements BookService {

    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(300);

    @Resource
    private MrBookRecordMapper bookRecordMapper;
    @Resource
    private MrUserMapper mrUserMapper;
    @Resource
    private MrMeetingRoomMapper mrMeetingRoomMapper;
    @Resource
    private MrBookRecordMapper mrBookRecordMapper;
    @Resource
    private MrMeetingRoomPasswordMapper mrMeetingRoomPasswordMapper;
    @Autowired
    private PasswordServiceImpl passwordService;

    /**
     * 预约旅行(需要判断当天的旅游单数是否超过了条件)
     * （比如一天只能有10次旅游预约记录，可在点击日期时就进行判断，通过checkService的方法）
     *
     * @param record 旅游记录
     * @return 返回成功信息，成功预约则返回预约记录
     */
    @Override
    public Result book(BookRecord record) {
        Result result = new Result();

        String userId = record.getUserId();

        int i = 0;


        //以下为添加新的记录，将mrBookRecord修改后改为我们数据库的内容在添加即可
        MrBookRecord mrBookRecord = new MrBookRecord();
        mrBookRecord.setId(IdUtils.get32Id());
        //预约几点开始
        mrBookRecord.setBookTime(new Date());

        MrUser mrUser = mrUserMapper.selectComidByPrimaryKey(record.getUserId());
        if (mrUser == null || Strings.isBlank(mrUser.getCompanyId())) {
            result.setSuccess(false);
            result.setErrorMessage("查找不到用户");
            return result;
        }
        mrBookRecord.setCompanyId(mrUser.getCompanyId());
        mrBookRecord.setGmtCreated(new Date());
        mrBookRecord.setGmtModified(new Date());
        mrBookRecord.setUserId(userId);
        mrBookRecord.setValid(true);

        Date duetime = new Date();
        duetime.setTime(mrBookRecord.getBookTime().getTime() + 30 * 60 * 1000);
        mrBookRecord.setDueTime(duetime);

        mrBookRecord.setMeetingRoomId(record.getMeetingRoomId());
        mrBookRecord.setOutnumber(record.getOutnumber());

        BookRecord mdbookRecord = new BookRecord();
        BeanUtils.copyProperties(mrBookRecord, mdbookRecord);
        i = bookRecordMapper.insert(mrBookRecord);
        if(i==0){
            result.setSuccess(false);
            result.setErrorMessage("存储预定信息失败");
            return result;
        }

        //修改会议室状态
        //修改一个bebooked状态
        i = mrMeetingRoomMapper.updateBookedByPrimaryKey(record.getMeetingRoomId(),true);

        if(i==0){
            bookRecordMapper.deleteByPrimaryKey(mrBookRecord.getId());
            result.setSuccess(false);
            result.setErrorMessage("预定后修改会议室状态失败");
            return result;
        }


        //预定的时候，创建密码记录，增加记录，创建ID

        MrMeetingRoomPassword mrMeetingRoomPassword = new MrMeetingRoomPassword();
        mrMeetingRoomPassword.setId(IdUtils.get32Id());


        //创建密码，并获取密码，以便给前端查看或者邮件发送
        Result generagePwd = passwordService.generagePwd(userId, meetingRoomId);
        if (!generagePwd.isSuccess()) {
            result.setSuccess(false);
            result.setErrorMessage("添加密码失败");
            return result;
        }
        //todo 发送密码邮件


        /*//计划任务
        scheduledExecutorService.schedule(() -> {
                //修改记录，有效变为无效
            if (mrBookRecordMapper.updateValidByPrimaryKey(mrBookRecord.getId(), false) == 0) {
                    result.setSuccess(false);
                    result.setErrorMessage("修改预定记录中的有效值");
                }
                //修改会议室表
            if (mrMeetingRoomMapper.updateBookedByPrimaryKey(record.getMeetingRoomId(), false) == 0) {
                    result.setSuccess(false);
                    result.setErrorMessage("预定后修改会议室状态失败");
                }
                //根据ID删除密码
            if (mrMeetingRoomPasswordMapper.deleteByMeetingRoomId(mrBookRecord.getMeetingRoomId()) == 0) {
                    result.setSuccess(false);
                    result.setErrorMessage("删除无效密码失败");
            }
            }, 30, TimeUnit.MINUTES);
*/
        result.setData(mdbookRecord);
        result.setSuccess(true);
        return result;
    }

    /**
     * 取消预约
     *
     * @param record 要给定预约记录主键
     * @return 是否成功取消预约
     */
    @Override
    public boolean cancel(BookRecord record) {
        String userId = record.getUserId();
        String id = record.getId();

        int i = 0;
        //查询详细信息
        MrBookRecord mrBookRecord = mrBookRecordMapper.selectByPrimaryKey(id);
        if(mrBookRecord==null){
            return false;
        }

        String meetingRoomId = mrBookRecord.getMeetingRoomId();
        //有效状态，会议室状态为租借状态，时间小于到期时间，满足以上条件代表为有效租借状态，可取消预约
        if (mrBookRecord.getValid()) {
            //修改记录，有效变为无效
            if(mrBookRecordMapper.updateValidByPrimaryKey(id,false)==0){
                return false;
            }
            //修改会议室表
            if(mrMeetingRoomMapper.updateBookedByPrimaryKey(meetingRoomId,false)==0){
                mrBookRecordMapper.updateValidByPrimaryKey(id,true);
                return false;
            }
            //根据userId删除密码
            if(mrMeetingRoomPasswordMapper.deleteByMeetingRoomId(meetingRoomId)==0){
                mrBookRecordMapper.updateValidByPrimaryKey(id,true);
                mrMeetingRoomMapper.updateBookedByPrimaryKey(meetingRoomId,true);
                return false;
            }
            return true;
        }

        //无满足条件得到数据
        return false;
    }

    /**
     * 获取预约信息
     *
     * @param record 旅游记录主键
     * @return 预约信息、成功信息
     */
    @Override
    public Result getBookInfo(BookRecord record) {
        Result result = new Result();
        String id = record.getId();
        MrBookRecord bookRecord = mrBookRecordMapper.selectByPrimaryKey(id);
        if(bookRecord==null){
            result.setSuccess(false);
            result.setErrorMessage("未找到记录");
            return result;
        }
        //回复信息
        BookRecord returnRecord = new BookRecord();
        String meetingRoomId = bookRecord.getMeetingRoomId();
        String meetingRoomName = mrMeetingRoomMapper.selectMeetingRoomNameByPrimaryKey(meetingRoomId);
        returnRecord.setMeetingRoomName(meetingRoomName);
        BeanUtils.copyProperties(bookRecord,returnRecord);
        result.setData(returnRecord);
        result.setSuccess(true);
        return result;
    }

    /**
     * 获取用户的所有预约记录
     *
     * @param userId 用户主键
     * @return 预约记录列表
     */
    @Override
    public Result getBookRecords(String userId) {
        Result result = new Result();

        List<MrBookRecord> mrBookRecords = mrBookRecordMapper.selectAllByUserID(userId);

        if (mrBookRecords.isEmpty()){
            result.setErrorMessage("无预约记录");
            result.setSuccess(false);
            return result;
        }
        List<BookRecord> returnList = new ArrayList<>();

        for (MrBookRecord mrBookRecord : mrBookRecords) {
            BookRecord record = new BookRecord();

            BeanUtils.copyProperties(mrBookRecord, record);
            String meetingRoomId = record.getMeetingRoomId();
            String name = mrMeetingRoomMapper.selectMeetingRoomNameByPrimaryKey(meetingRoomId);
            record.setMeetingRoomName(name);

            returnList.add(record);
        }
        result.setData(returnList);
        result.setSuccess(true);
        return result;
    }
}